/** @format */

const { src, dest, series, parallel, watch } = require("gulp");
const htmlMin = require("gulp-htmlmin");
const babel = require("gulp-babel");
const terser = require("gulp-terser");
const less = require("gulp-less");
const inject = require("gulp-inject");

const browserSync = require("browser-sync");

const htmlTast = () => {
  return src("./src/**/*.html")
    .pipe(htmlMin({ collapseWhitespace: true })) // 折叠空白字符
    .pipe(dest("./dist"));
};
const jsTast = async () => {
  await src("./src/**/*.js")
    .pipe(babel({ presets: ["@babel/preset-env"] })) //使用babel
    .pipe(terser({ mangle: { toplevel: true } })) // 优化代码
    .pipe(dest("./dist")); //拷贝所有文件
};

// 处理less文件（将less转为css）
const lessTast = () => {
  return src("./src/**/*.less").pipe(less()).pipe(dest("./dist"));
};

// 將 js、css文件注入html文件中
const injectTast = () => {
  return src("./dist/**/*.html")
    .pipe(inject(src(["./dist/**/*.js", "./dist/**/*.css"]), { relative: true }))
    .pipe(dest("./dist"));
};

// 构建任务
const buildTast = series(parallel(htmlTast, jsTast, lessTast), injectTast);

// 使用browser-sync创建服务实现热更新
const bs = browserSync.create();
const server = () => {
  watch("./src/**", buildTast);
  bs.init({
    port: 8080,
    open: true, //是否打开浏览器
    files: "./dist/*", //监听的文件目录
    server: {
      baseDir: "./dist", //开启服务的资源目录
    },
  });
};

const serverTast = series(buildTast, server);

module.exports = {
  buildTast,
  serverTast,
};
